package com.zhkj.txg.module.home.adapter

import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.zhkj.lib.utils.ScreenUtil
import com.zhkj.txg.module.home.entity.NavigationEntity
import kotlin.math.min

class HomeBannerCateAdapter(
    private val spanCount: Int,
    private val rowsCount: Int,
    private val onCLick: (item: NavigationEntity) -> Unit
) : RecyclerView.Adapter<HomeCateViewHolder>() {

    val data = mutableListOf<NavigationEntity>()

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HomeCateViewHolder {
        return HomeCateViewHolder(spanCount, RecyclerView(parent.context).apply {
            isNestedScrollingEnabled = false
            hasFixedSize()
            setPadding(ScreenUtil.dip(context, 20), 0, 0, 0)
            layoutParams = RecyclerView.LayoutParams(
                RecyclerView.LayoutParams.MATCH_PARENT,
                RecyclerView.LayoutParams.MATCH_PARENT
            )
        }, onCLick)
    }

    override fun getItemCount(): Int {
        val pageTotalItem = spanCount * rowsCount
        return if (data.size % pageTotalItem == 0) data.size / pageTotalItem else data.size / pageTotalItem + 1
    }

    override fun onBindViewHolder(holder: HomeCateViewHolder, position: Int) {
        val pageTotalItem = spanCount * rowsCount
        val list = mutableListOf<NavigationEntity>()
        data.forEachIndexed { index, navigationEntity ->
            if (index >= pageTotalItem * position && index < min(pageTotalItem * (position + 1), data.size)) {
                list.add(navigationEntity)
            }
        }
        holder.cateAdapter.setNewData(list)
    }

    fun setNewData(list: MutableList<NavigationEntity>) {
        data.addAll(list)
        notifyDataSetChanged()
    }
}

class HomeCateViewHolder(
    private val spanCount: Int,
    view: View,
    private val onCLick: (item: NavigationEntity) -> Unit
) : RecyclerView.ViewHolder(view) {
    val cateAdapter = HomeCateAdapter().apply {
        setOnItemClickListener { _, _, position ->
            onCLick(data[position])
        }
    }

    init {
        with(itemView as RecyclerView) {
            layoutManager = GridLayoutManager(context, spanCount)
            adapter = cateAdapter
        }
    }
}